package com.ws.service.serviceImpl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServer;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.stereotype.Service;

import com.ws.bean.MailRequest;
import com.ws.bean.User;
import com.ws.dao.UserDao;
import com.ws.service.UserService;
import com.ws.util.DigestUtil;
import com.ws.util.JWTUtil;
import com.ws.util.Page;
@Service
public class UserServiceImp implements UserService {

	@Autowired
	UserDao dao;
	
	public static void main(String[] args) {
		//md5加密
		//可以多次加密
		//随机次数加密
		//盐值加密
		String pass = "123";
		String digestPass = DigestUtils.md5Hex(pass);
		System.out.println(digestPass);
		
		String pass1 = "123";
		String digestPass1 = DigestUtils.md5Hex(pass1);
		System.out.println(digestPass1);
		
		String pass2 = "123" + "a";
		for(int i = 0;i < 20;i++) {
			pass2 = DigestUtils.md5Hex(pass2);
		}
		System.out.println(pass2);
		
	}
	private boolean checkPassword(String password,String password_data) {
		System.out.println(DigestUtil.decode(password, password_data));
		return DigestUtil.decode(password, password_data);
	}
	@Override
	public String doLogin(User user) {
		//1.获取数据库中的数据  byname
		
		List<User> list = dao.getUserByUsername(user.getUsername());
		if(list.size() == 1) {
			User user_data = list.get(0);
			//2.比较密码
			boolean bool = checkPassword(user.getPassword(), user_data.getPassword());
			if(bool) {
				//3.成功后生成token
				return JWTUtil.createToken(null);
			}
			//4.
			return null;
		}
		return null;
	}
	@Override
	public List<User> getUser(User user, Page page) {
		return dao.getUser(user , page);
	}
	@Override
	public int getCount(User user) {
		return dao.getCount(user);
	}
	@Override
	public int delUser(Integer id) {
		return dao.delUser(id);
	}
	@Override
	public int editUser(User user) {
		return dao.editUser(user);
	}
	@Override
	public int addUser(User user) {
		return dao.addUser(user);
	}
	@Override
	public int editPssword(User user) {
		List<User> list = dao.getUserByUsername(user.getUsername());
		if(list.size() == 1) {
			User user_data = list.get(0);
			if(checkPassword(user.getPassword(), user_data.getPassword())) {
				System.out.println("两次的密码一致");
				user.setNewpassword(DigestUtil.randomDigest(user.getNewpassword()));
				return dao.editPassword(user);
			}
		}
		return 0;
	}
	@Override
	public void setUser(MailRequest mailRequest) {
		dao.setUser(mailRequest);
	}
	
	

}
